package com.yf.gogameserver.controller;/*
@author FAN

@create 2021-12-22-17:14


*/

import com.yf.gogameserver.service.IUserService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


@RestController
@CrossOrigin
public class ImgController {

    @Autowired
    private IUserService userService;

    /**
     * 图片的上传路径
     * 重来一便
     */
    private String path = "D:\\imag\\";

    /**
     * 删除图片
     *
     * @return 返回图片的上传后的名称
     */
    @RequestMapping("/img/uploader")
    public String uploaderImg(MultipartFile file, String username) {

        System.out.println("获取到上传的数据" + username);

        //基于UUID生成一个文件名称（防止上传的图片重复）
        String fileName = UUID.randomUUID().toString();

        //IO流
        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(path + fileName);
        ) {
            IOUtils.copy(in, out);

            //最新的头像名称，更新到数据库
            userService.updateHeader(username, fileName);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }

    /**
     * 通过图片名称 获取图片的内容
     *
     * @param imgName
     */
    @RequestMapping("/img/getImg")
    public void getImg(String imgName, HttpServletResponse response) {
        //获取本地的图片
        try (
                InputStream in = new FileInputStream(path + imgName);
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
